#coding:utf8
__author__ = 'Wishchen'

import time
import os
import sys
import requests
import json
import subprocess
import ConfigParser
from config.settings import *
from log import *

reload(sys)
sys.setdefaultencoding('utf8')


class Docker(object):
    """
    Docker类
    """
    def __init__(self, url):
        self.url = url
        self.device = configPath + "/" + url
        self.cf = ConfigParser.ConfigParser()

    def docker(self, action, **rule):
        """
        启动docker容器，启动对应端口anyproxy(不同过滤规则)，取回log, kill容器
        :param action: run 启动镜像容器 默认开启anyproxy过滤 kill 杀掉镜像容器 anyproxy 切换过滤规则
        :param rule: 空值: 只启动anyproxy 非空: 为anyproxy过滤规则js文件名
        :return:
        """
        nowtime = time.strftime('%Y%m%d_%H%M%S')
        # 获取配置文件中aport端口号做容器与宿主机间转发
        self.cf.read(self.device)
        info = dict(self.cf.items("device"))
        device_id = info["deviceid"]
        port = info["port"]
        bport = info["bport"]
        aport = info["aport"]
        waport = int(aport) + 1
        log.info("device_id:%s port:%s bport:%s aport:%s waport:%s" % (device_id, port, bport, aport, waport))

        start_docker = "docker run -p %s:8001 -p %d:8002 -d -i -v %s:/home/anyproxy -v %s:/home/log node:6.15  /bin/bash " % (aport, waport, ANYPROXY, LOG)
        # -d 不销毁 -i 交互模式运行容器 -t 容器启动后进入命令行 -v 挂载
        get_containerId = "docker ps | grep %s | awk {'print $1'}" % aport
        docker_exec = "docker exec "


        if action == "run":
            # 启动对应端口转发的容器
            log.info("开始启动docker服务")
            self.execcommand(start_docker)
            log.info("启动docker容器命令：" + start_docker)
        elif action == "anyproxy":
            # 启用不同的过滤规则文件
            rule = rule['rule']
            log.info("启动anyproxy服务，应用rule文件为：" + rule)
            log.info("获取占用%s端口的容器名称" % aport)
            containerID = self.execcommand(get_containerId)
            if containerID == "":
                log.info("无占用%s端口的容器，开始启动容器" % aport)
                self.execcommand(start_docker)
                containerID = self.execcommand(get_containerId)
                log.info("docker启动容器成功，容器名称：%s" % containerID)
            else:
                pass
            cmd1 = " anyproxy "
            cmd2 = " anyproxy --intercept --rule /home/anyproxy/android/jiekuan_all/rule/"
            grep_anyproxy = " ps -ef | grep anyproxy | awk {'print $2'} "
            kill_pid = " kill -9 "
            logPath = " >/home/log/anyproxy%s.log" % nowtime

            # 先杀掉anyproxy
            log.info("开始查找容器中启动的anyproxy服务")
            docker_exec_grep_anyproxy = docker_exec + containerID + grep_anyproxy
            pid = self.execcommand(docker_exec_grep_anyproxy)
            ppid = pid.split()
            log.info("anyproxy进程id：%s" % ppid)

            if pid == "":
                pass
            else:
                # 循环杀掉anyproxy相关进程pid
                for i in range(len(ppid)):
                    docker_exec_kill_pid = docker_exec + containerID + kill_pid + ppid[i]
                    log.info("杀掉anyproxy服务，进程id：%s" % ppid)
                    self.execcommand(docker_exec_kill_pid)

            # 设置anyproxy启动路径
            path = self.url.split("_")[0]
            log.info("anyproxy路径类型：%s" % path)

            # 根据不同规则启动anyproxy
            if rule == "":
                docker_exec_cmd = docker_exec + containerID + " sh /home/anyproxy/android/%s/rule/anyproxy.sh" % path
                log.info("容器中启动anyproxy，action：%s" % docker_exec_cmd)
                time.sleep(2)
                self.execcommand2(docker_exec_cmd)
            elif rule == "rule.js":
                docker_exec_cmd = docker_exec + containerID + " sh /home/anyproxy/android/%s/rule/rule.sh" % path
                log.info("容器中启动anyproxy，action：%s" % docker_exec_cmd)
                time.sleep(2)
                self.execcommand2(docker_exec_cmd)
            elif rule == "a.js":
                docker_exec_cmd = docker_exec + containerID + " sh /home/anyproxy/android/%s/rule/a.sh" % path
                log.info("容器中启动anyproxy，action：%s" % docker_exec_cmd)
                time.sleep(2)
                self.execcommand2(docker_exec_cmd)
            else:
                log.error(u"anyproxy过滤规则rule有误")
                return


        elif action == "kill":
            # 结束容器
            containerID = self.execcommand(get_containerId)
            log.info("结束容器，容器id：%s" % containerID)
            if containerID == "":
                log.warning("没有运行转发端口%s的容器" % aport)
                return
            else:
                pass
            # localLogPath = "/Users/chenws/Documents/weshare/log/" + aport + "_" + nowtime
            # mkdir_cmd = "mkdir " + localLogPath
            # execcommand(mkdir_cmd)
            # cp_cmd = "docker cp %s:/home/alog %s" % (containerID, localLogPath)
            kill_cmd = "docker kill " + containerID
            rm_cmd = "docker rm " + containerID
            # execcommand(cp_cmd)
            time.sleep(3)
            self.execcommand(kill_cmd)
            self.execcommand(rm_cmd)
            log.info("结束容器完成")
        else:
            log.error(u"输入有误")
            raise Exception(u'输入错误')

    def execcommand(self, command):
        log.info("执行命令：" + command)
        p = os.popen(command).read()
        commandRes = p.strip()
        time.sleep(5)
        if commandRes:
            log.info("执行结果" + commandRes)
            return commandRes
        else:
            log.info("命令执行结果内容为空")
            return ""

    def execcommand2(self, comand):
        # 以shell方式执行命令，用来执行anyproxy命令
        log.info("shell命令：" + comand)
        subprocess.Popen(comand, shell=True)
        time.sleep(20)


if __name__ == "__main__":
    pass